﻿using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Eff.Utils
{
    /// <summary>
    /// 正则表达式帮助类
    /// </summary>
    public class RegexHelper
    {
        private static readonly Dictionary<string, Regex> _rexDic;
        static RegexHelper()
        {
            _rexDic = new Dictionary<string, Regex>(20);
        }
        /// <summary>
        /// 注册一个表达式
        /// </summary>
        /// <param name="regexKey"></param>
        /// <param name="regexPattern"></param>
        public static void Add(string regexKey, string regexPattern)
        {
            if (!_rexDic.ContainsKey(regexKey))
                _rexDic.Add(regexKey, new Regex(regexPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase));
        }

        /// <summary>
        /// 返回匹配到的值,匹配失败返回string.Empty
        /// </summary>
        /// <param name="regexKey"></param>
        /// <param name="input"></param>
        /// <param name="beginning"></param>
        /// <param name="length"></param>
        /// <param name="matchItemIndex"></param>
        /// <returns></returns>
        public static string GetMatchValue(string regexKey, string input, int beginning = 0, int? length = null, int matchItemIndex = 0)
        {
            length = length ?? input.Length;
            var regex = _rexDic[regexKey];
            var match = regex.Match(input, beginning, length.Value);
            if (match.Success)
                return match.Groups[matchItemIndex].Value;
            return string.Empty;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <param name="pattern"></param>
        /// <returns></returns>
        public static bool IsMatch(string input, string pattern)
        {
            return Regex.IsMatch(input, pattern);
        }
    }

}
